<template>
    <div class="children_content">
        <div class="add_btns_box">
            <div class="box_left">
                <Space>
                    流程名称:
                    <Input v-model="flowName"></Input>
                </Space>
            </div>
            <div class="box_right">
                <Button type="success" @click="saveFlow">保存</Button>
            </div>
        </div>
        <div class="flow_content">
            <template v-for="(item, index) in flowList" :key="item.level">
                <div class="item_box">
                    <div class="arrow" v-if="item.type != 0"></div>
                    <Card style="width: 200px" v-if="item.type != 4" :class="'flex_card' + item.type" @click="openDrawer(item.type, item, item.level)">
                        <template #title>
                            <Icon :type="item.type == 3 ? 'ios-send' : 'md-contact'"></Icon>
                            {{ item.nodeName }}
                        </template>
                        <template #extra v-if="item.type != 0">
                            <Icon type="ios-close" size="20" @click.stop="delNode(item.level)" />
                        </template>
                        <p class="rate-demo">
                            <Ellipsis :text="showCardName(item.type, item)" :lines="1" tooltip />
                        </p>
                    </Card>
                    <div class="add_btn" v-if="item.type != 4">
                        <div class="line"></div>
                        <Poptip placement="right" width="250">
                            <Button type="primary" shape="circle" icon="md-add" :key="item.level" />
                            <template #content>
                                <div class="popup_box">
                                    <div class="item" @click="addNode(2, item.level)">
                                        <Icon type="md-contact" style="color: #ff9900;" />
                                        <div class="title">审核节点</div>
                                    </div>
                                    <div class="item" @click="addNode(3, item.level)">
                                        <Icon type="ios-send" style="color: #2d8cf0;" />
                                        <div class="title">抄送节点</div>
                                    </div>
                                    <div class="item" @click="addNode(4, item.level)">
                                        <Icon type="md-git-merge" style="color: #19be6b;" />
                                        <div class="title">条件节点</div>
                                    </div>
                                </div>
                            </template>
                        </Poptip>
                    </div>
                </div>
                <div v-if="item.type == 4">
                    <div class="condition_add">
                        <div class="left_line" v-if="item.conditionList.length > 1"
                            :style="{ width: setLineWidth(item.conditionList) }">
                        </div>
                        <Button type="success" ghost @click="addConditionPoint(item.level)">添加条件</Button>
                        <div class="right_line" v-if="item.conditionList.length > 1"
                            :style="{ width: setLineWidth(item.conditionList) }">
                        </div>
                    </div>
                    <div class="condition_box">
                        <div class="condition_item" v-for="(condition, indexTwo) in item.conditionList">
                            <div class="condition_line"></div>
                            <div class="condition_bottom_left_line" v-if="indexTwo != 0"></div>
                            <div class="condition_bottom_right_line" v-if="indexTwo != item.conditionList.length - 1">
                            </div>
                            <Card style="width: 200px" class="condition_card" @click="openConditionEdit(condition, item.level, indexTwo)">
                                <template #title>
                                    <Icon type="ios-git-merge"></Icon>
                                    {{ condition.nodeName }}
                                </template>
                                <template #extra>
                                    优先级: {{ condition.priorityLevel }}
                                    <Icon type="ios-close" size="20"
                                        @click.stop="delConditionNode(item.level, condition.priorityLevel)" />
                                </template>
                                <p class="rate-demo">
                                    <Ellipsis :text="showConditionLabelStr(condition.conditionList)" :lines="1" tooltip />
                                </p>
                            </Card>
                            <div class="add_btn" style="height: 50px;">
                                <div class="line"></div>
                                <!-- <Poptip placement="right" width="250">
                                    <Button type="primary" shape="circle" icon="md-add" :key="indexTwo" />
                                    <template #content>
                                        <div class="popup_box">
                                            <div class="item">
                                                <Icon type="md-contact" style="color: #ff9900;" />
                                                <div class="title">审核节点</div>
                                            </div>
                                            <div class="item">
                                                <Icon type="ios-send" style="color: #2d8cf0;" />
                                                <div class="title">抄送节点</div>
                                            </div>
                                            <div class="item">
                                                <Icon type="md-git-merge" style="color: #19be6b;" />
                                                <div class="title">条件节点</div>
                                            </div>
                                        </div>
                                    </template>
                                </Poptip> -->
                            </div>
                        </div>
                    </div>
                    <div class="add_btn condition_add_btn">
                        <div class="line"></div>
                        <Poptip placement="right" width="250">
                            <Button type="primary" shape="circle" icon="md-add" :key="item.level" />
                            <template #content>
                                <div class="popup_box">
                                    <div class="item" @click="addNode(2, item.level)">
                                        <Icon type="md-contact" style="color: #ff9900;" />
                                        <div class="title">审核节点</div>
                                    </div>
                                    <div class="item" @click="addNode(3, item.level)">
                                        <Icon type="ios-send" style="color: #2d8cf0;" />
                                        <div class="title">抄送节点</div>
                                    </div>
                                    <div class="item" @click="addNode(4, item.level)">
                                        <Icon type="md-git-merge" style="color: #19be6b;" />
                                        <div class="title">条件节点</div>
                                    </div>
                                </div>
                            </template>
                        </Poptip>
                    </div>
                </div>
            </template>
            <div class="end_flow">
                <div class="point"></div>
                <div class="label">结束节点</div>
            </div>
        </div>
    </div>
    <conditionEdit v-model="showCondition" :data="conditionObj" @changeVisible="saveCondition" />
    <initiateEdit v-model="showInitiate" :data="initiateObj" @changeVisible="saveInitiate" />
    <sendCopyEdit v-model="showSendCopy" :data="sendCopyArr" @changeVisible="saveSendCopy" />
    <approveEdit v-model="showApprove" :data="approveObj" @changeVisible="saveApprove" />
</template>

<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue';
import conditionEdit from './conditionEdit.vue';
import initiateEdit from './initiateEdit.vue';
import sendCopyEdit from './sendCopyEdit.vue';
import approveEdit from './approveEdit.vue';

const { proxy } = getCurrentInstance();

// 流程名称
const flowName = ref('自定义流程');

// 是否显示条件弹框
const showCondition = ref(false);

// 是否显示发起人弹框
const showInitiate = ref(false);

// 是否显示抄送人弹框
const showSendCopy = ref(false);

// 是否显示审批配置弹框
const showApprove = ref(false);

// 临时条件对象
const conditionObj = ref(null);

// 临时发起人对象
const initiateObj = ref(null);

// 临时抄送人数组
const sendCopyArr = ref([]);

// 临时审批对象
const approveObj = ref(null)

// 临时层级
const temporaryLevel = ref(null);

// 临时条件对象下标
const temporaryIndex = ref(null);

/**
 * tpye: 0 // 开始节点,不可删除
 * type: 1 // 条件节点, 可删除
 * type: 2 // 审核节点, 可删除
 * type: 3 // 抄送节点, 可删除
 * type: 4 // 条件路由, 根据条件节点自动生成
 * type: 5 // 结束节点, 不可删除,不显示,最后加入到最底层childrenNode即可
*/
const flowObj = ref({});

// 流程数组
const flowList = ref([
    { nodeName: '发起人', type: 0, userInfo: {}, level: 0 },
]);

// 用户列表
// 用户列表
const userInfoList = ref([
    { userName: '张三', id: '1' },
    { userName: '李四', id: '2' },
    { userName: '王五', id: '3' }
]);

/**
 * 设置线条宽度
 * @param lst 条件节点数组
 */
const setLineWidth = (lst) => {
    if (lst.length > 2) {
        let num = lst.length - 2;
        return (num * 200 + 155) + 'px';
    } else {
        return '155px';
    }
}

/**
 * 回显条件文字
 * @param lst 条件列表
 * @returns 返回拼接字符串
*/
const showConditionLabelStr = (lst) => {
    if (lst.length) {
        let newLst = lst.map(item => item.label );
        return newLst.toString();
    } else {
        return '请设置条件'
    }
}

/**
 * 回显节点用户文字
 * @param {
 *  type: 0 发起人节点，2 审核节点， 3 抄送节点
 *  obj: 数据对象
 * }
 * @returns 返回拼接字符串
 */
const showCardName = (type, obj) => {
    if (type == 0) { // 发起人节点
        return obj.userInfo && obj.userInfo.userName ? obj.userInfo.userName : '请选择发起人';
    } else if (type == 2){ // 审批节点
        let newLst = null;
        if (obj.userList && obj.userList.length) {
            newLst = obj.userList.map(item => {
                let index = userInfoList.value.findIndex(itemTwo => itemTwo.id == item);
                return userInfoList.value[index].userName;
            });
            return newLst.toString();
        } else {
            return '请选择审批人';
        }
    } else if (type == 3) { // 抄送人节点
        let nameList = obj.userList.map(item => {
            let index = userInfoList.value.findIndex(itemTwo => itemTwo.id == item);
            return userInfoList.value[index].userName;
        })
        return nameList.toString();
    }
}

/**
 * 添加条件路由节点
 * @param level 层级下标
 * */
const addConditionPoint = (level) => {
    flowList.value[level].conditionList.push({ 
        nodeName: '条件' + (flowList.value[level].conditionList.length + 1),
        type: 1,
        conditionList: [],
        priorityLevel: (flowList.value[level].conditionList.length + 1)
    });
}

/**
 * 删除条件路由节点
 * @param {
 *  level: 层级下标
 *  index: 优先级
 * }
*/
const delConditionNode = (level, index) => {
    if (flowList.value[level].conditionList.length == 1) {
        flowList.value.splice(level, 1);
        flowList.value.forEach((item, index) => {
            item.level = index;
        });
    } else {
        flowList.value[level].conditionList.splice(index - 1, 1);
        flowList.value[level].conditionList.forEach((item, index) => {
            item.priorityLevel = (index + 1);
        });
    }
}

/**
 * 添加节点
 * @param {
 *  type: 节点类型,
 *  level: 层级
 * }
*/
const addNode = (type, level) => {
    let obj = null;
    if (type == 2) { // 审核节点
        obj = {
            nodeName: '审核节点', // 节点名称
            type: type, // 节点类型
            level: (level + 1), // 层级
            userList: [], // 审核人员
            isOvertime: false, // 是否超时自动审批 false 否，true 是
            overtime: 0, // 如isOvertime = true时, overtime为审批时限，0则不生效
            autoPass: 0, // 如isOvertime = true时, autoPass为期限后自动审批类型 0: 自动通过, 1: 自动拒绝
            multiUser: 0, // 多人审批时的审批方式类型 0: 按顺序依次审批, 1: 会签(可同时审核，每个人必须审批通过), 2: 或签(有一人审批通过即可)
        };
    } else if (type == 3) { // 抄送节点
        obj = {
            nodeName: '抄送节点', // 节点名称
            type: type, // 节点类型
            level: (level + 1), // 层级
            userList: [], // 抄送人员
        };
    } else if (type == 4) { // 条件节点
        obj = {
            nodeName: '条件路由', // 节点名称
            type: type, // 节点类型
            level: (level + 1), // 层级
            conditionList: [ // 条件数组
                { nodeName: '条件1', type: 1, conditionList: [], priorityLevel: 1, mode: 1 }
            ],
        };
    }
    flowList.value.splice(level + 1, 0, obj);
    flowList.value.forEach((item, index) => {
        item.level = index;
    });
}


/**
 * 删除节点
 * @param level 层级下标
*/
const delNode = (level) => {
    flowList.value.splice(level, 1);
    flowList.value.forEach((item, index) => {
        item.level = index;
    });
}

/**
 * 生成节点树
 * @param {arr: 节点数组}
*/
const buildTree = (arr) => {
    if (arr.length === 0) {
        return null;
    }

    function recurse(nodes) {
        if (nodes.length === 0) {
            return null;
        }

        let currentNode = { ...nodes[0] }; // 复制当前节点
        let nextNodes = nodes.slice(1); // 获取剩余节点

        if (nextNodes.length > 0) {
            currentNode.childrenNode = recurse(nextNodes); // 递归处理剩余节点
        } else {
            delete currentNode.childrenNode; // 如果没有子节点，则删除childrenNode属性（可选）
        }

        return currentNode;
    }

    return recurse(arr);
}

/**
 * 打开弹框
 * @param {
 *  type: 打开类型: 0 发起人节点，2 审核节点， 3 抄送节点
 *  obj: 当前对象
 *  level: 当前层级
 * }
 */
const openDrawer = (type, obj, level) => {
    temporaryLevel.value = level;
    if (type == 0) { // 发起人节点
        // console.log('%csrc\pages\approvalFlow\index.vue:393 object', 'color: #007acc;', userInfo);
        // return
        initiateObj.value = obj.userInfo;
        showInitiate.value = true;
    } else if (type == 2) { // 审核节点
        approveObj.value = obj;
        showApprove.value = true;
    } else if (type == 3) { // 抄送节点
        sendCopyArr.value = obj.userList;
        showSendCopy.value = true;
    }
}

/**
 * 打开编辑条件弹框
 * @param {
 *  item: 当前对象
 *  level: 层级
 *  index: 当前对象下标
 * }
*/
const openConditionEdit = (item, level, index) => {
    temporaryLevel.value = level;
    temporaryIndex.value = index;
    conditionObj.value = item;
    showCondition.value = true;
}

/**
 * 保存条件配置
 * @param val 返回值
*/
const saveCondition = (val) => {
    showCondition.value = false;
    let level = temporaryLevel.value;
    let index = temporaryIndex.value;
    flowList.value[level].conditionList[index] = val;
    conditionObj.value = null;
    temporaryLevel.value = null;
    temporaryIndex.value = null;
}

/**
 * 保存发起人配置
 * @param val 返回值
 */
const saveInitiate = (val) => {
    showInitiate.value = false;
    let level = temporaryLevel.value;
    flowList.value[level].userInfo = val;
    initiateObj.value = null;
    temporaryLevel.value = null;
    temporaryIndex.value = null;
}

/**
 * 保存抄送人配置
 * @param val 返回值
 */
const saveSendCopy = (val) => {
    showSendCopy.value = false;
    let level = temporaryLevel.value;
    flowList.value[level].userList = val.userList;
    sendCopyArr.value = null;
    temporaryLevel.value = null;
    temporaryIndex.value = null;
}

/**
 * 保存审核节点配置
 * @param val 返回值
 */
const saveApprove = (val) => {
    showApprove.value = false;
    let level = temporaryLevel.value;
    // flowList.value[level].userList = val.userList;
    approveObj.value = null;
    temporaryLevel.value = null;
    temporaryIndex.value = null;
}

// 保存流程
const saveFlow = () => {
    proxy.$Message.success('请按F12查看数据格式');
    console.log('%csrc\pages\approvalFlow\index.vue:479 object', 'color: #007acc;', {
        flowName: flowName.value,
        nodes: buildTree(flowList.value)
    });
}

onMounted(() => {
    
})
</script>